package com.app.car.check;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.app.car.R;
import com.app.car.bean.RfidListBean;
import com.app.car.check.info.CheckTabActivity;
import com.app.car.greendao.GreenDaoUtils;
import com.app.car.home.HomeBaseActivity;
import com.app.car.home.HomeTabActivity;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import my.ActivityTool;
import my.DialogUtils;
import my.TimeUtils;

/**
 * 盘点单
 */
public class CheckListActivity extends HomeBaseActivity implements CheckView{

    CheckPresent present;
    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;

    private MyAdapterList mAdapter;
    private List<RfidListBean> mListBean;

    @Override
    public void refresh() {
        super.refresh();
        getList();
    }

    @Override
    public void initViews() {
        setContentView(R.layout.check_list_activity);
        super.initViews();
        present = new CheckPresentImpl(this,this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadingMoreEnabled(false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBean = new ArrayList<>();
        setListView();
        getList();
    }


    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        setEmptyView();
    }


    private void setEmptyView() {
        if (mListBean == null || mListBean.size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
            findViewById(R.id.refresh_view).setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            mRecyclerView.refresh();
                        }
                    });
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
        }
    }


    private void getList() {
        showLoading("刷新中！");

        Observable.create(new ObservableOnSubscribe<Integer>() {
            // 1\. 创建被观察者 & 生产事件
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                mListBean = GreenDaoUtils.getRfidListBean();
                emitter.onNext(1);
                emitter.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    // 2\. 通过通过订阅（subscribe）连接观察者和被观察者
                    // 3\. 创建观察者 & 定义响应事件的行为
                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                    // 默认最先调用复写的 onSubscribe（）

                    @Override
                    public void onNext(Integer value) {
                        dismissProgress();
                        setListView();

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.check_list_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_all)
            public TextView text_all;   //账面数
            @BindView(R.id.text_check)
            public TextView text_check;   //已盘数
            @BindView(R.id.text_pan_ying)
            public TextView text_pan_ying;   //盘盈
            @BindView(R.id.text_pan_kui)
            public TextView text_pan_kui;   //盘盈
            @BindView(R.id.text_title)
            public TextView text_title;   //标题
            @BindView(R.id.btn_info)
            public TextView btn_info;   //详情按钮
            @BindView(R.id.btn_out)
            public TextView btn_out;   //导出
            @BindView(R.id.btn_check_again)
            TextView btn_check_again;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                RfidListBean data = mListBean.get(position);
                btn_check_again.setVisibility(View.VISIBLE);
                text_all.setText(""+data.getBookRfidList().size());
                text_check.setText(""+data.getCheckRfidList().size());
                text_pan_ying.setText(""+data.getPanYingList().size());
                text_pan_kui.setText(""+data.getPanKuiList().size());
                text_title.setText("盘点单"+ TimeUtils.getTimeLongToStrByFormat(data.getTime(),"yyyy/MM/dd,HH:mm:ss"));
                btn_info.setTag(data);
                btn_out.setTag(data);
                btn_check_again.setTag(data);
                list_item.setTag(data);
            }
            @OnClick(R.id.btn_info)
            void onBtnInfoClick(View view){
                RfidListBean data = (RfidListBean) view.getTag();
                Bundle extras = new Bundle();
                extras.putLong("id",data.getId());
                ActivityTool.skipActivity(mContext, CheckTabActivity.class,extras);
            }

            @OnClick(R.id.btn_out)
            void onBtnOutClick(View view){
                RfidListBean data = (RfidListBean) view.getTag();
                present.exportExcel(data);
            }

            @OnClick(R.id.btn_check_again)
            void onCheckAgainClick(View view){

                showLoading("导入中");

                Observable.create(new ObservableOnSubscribe<RfidListBean>() {
                    // 1\. 创建被观察者 & 生产事件
                    @Override
                    public void subscribe(ObservableEmitter<RfidListBean> emitter) throws Exception {
//                        RfidListBean rfidBean = (RfidListBean) view.getTag();
//                        rfidBean.addBean(rfidBean.checkRfidList,"D6117076","2");
//                        rfidBean.addBean(rfidBean.checkRfidList,"D6117084","2");

                        String b = JSON.toJSONString((RfidListBean) view.getTag());
                        RfidListBean data = JSON.parseObject(b,RfidListBean.class);
                        emitter.onNext(data);
                        emitter.onComplete();
                    }
                })   .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<RfidListBean>() {
                            // 2\. 通过通过订阅（subscribe）连接观察者和被观察者
                            // 3\. 创建观察者 & 定义响应事件的行为
                            @Override
                            public void onSubscribe(Disposable d) {

                            }
                            // 默认最先调用复写的 onSubscribe（）

                            @Override
                            public void onNext(RfidListBean data) {
                                dismissProgress();
                                HomeTabActivity.EventHomeTab object = new HomeTabActivity.EventHomeTab(1);
                                EventBus.getDefault().post(object);

                                CheckIndexActivity.EventCheck eventCheck = new CheckIndexActivity.EventCheck(data);
                                EventBus.getDefault().post(eventCheck);

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

            }

            @OnLongClick(R.id.list_item)
            public boolean onItemLongClick(View v) {
                RfidListBean data = (RfidListBean) v.getTag();
                DialogUtils.showWarningDialog(mContext,"是否删除当前盘点单？","删除", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        GreenDaoUtils.rfidBeanDeleteData(data);
                        sweetAlertDialog.dismiss();
                        showToast("删除成功");
                        getList();
                    }
                });
                return true;
            }

        }
    }



    @OnClick({R.id.view_clear})
    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.view_clear:
                DialogUtils.showWarningDialog(mContext, "是否全部删除？", "确定", new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        GreenDaoUtils.clearAll();
                        getList();
                    }
                });
                break;


        }
    }
}
